package main

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"mongoDemo/common"
	"mongoDemo/parameter"
	"time"
)

func (app *application) insertSummary(ctx iris.Context) {
	var parameter parameter.InitParameter
	err := ctx.ReadJSON(&parameter)
	if err != nil {
		_ = ctx.JSON(common.Failed(err.Error()))
		return
	}
	err = app.mongo.DeleteBlockchain(parameter)
	if err != nil {
		_ = ctx.JSON(common.Failed(err.Error()))
		return
	}

	if parameter.DateTime == "" {
		parameter.DateTime = fmt.Sprintf("%s", time.Now().Format("2006-01-02 15:04:05"))
	}
	parameter.Hash = common.Hash(time.Now().String())

	err = app.mongo.AddBlockchain(parameter)
	if err != nil {
		_ = ctx.JSON(common.Failed(err.Error()))
		return
	}
	_ = ctx.JSON(common.Succeed(parameter.Hash))
}

func (app *application) getScores(ctx iris.Context) {
	scores, err := app.mongo.GetScores()
	if err != nil {
		_ = ctx.JSON(common.Failed(err.Error()))
		return
	}
	_ = ctx.JSON(scores)
}

func (app *application) queryScores(ctx iris.Context) {
	microserviceId := ctx.URLParam("microserviceId")
	user := ctx.URLParam("user")
	scores, err := app.mongo.QueryByMicroserviceId(microserviceId, user)
	if err != nil {
		_ = ctx.JSON(common.Failed(err.Error()))
		return
	}
	_ = ctx.JSON(scores[0])
}
